<?php

class Lances_M extends I_Model {

    protected $_table_name = 'lances';
    protected $_primary_key = 'ID';
    protected $_primary_filter = 'intval';
    protected $_order_by = 'ID';
    protected $_direction = 'DESC';
    public $rules = array();
    protected $_timestamps = FALSE;

    public function __construct() {
        parent::__construct();
    }

     
    /* add
     * Função responsavel pela por adicionar o lance do no sistema.
     * Enquanto a operação não foi realizada o sistema não retornará nada.
     * @param int $id codigo do lote
     * @param int $user  codigo do usuario
     * @param int $multiply numero multiplicador do lance.
     */
    function add($id, $user, $multiply = 1) {
        $data = array();
        $this->db->trans_start();
        //is not arrematado.
        if ($this->db->get_where('lances_arrematados', array('LOTE_ID' => $id))->num_rows() > 0) {
            return false;
        }
        //if not exists in lances_arrematados
        $this->db->select('lt.*,lc.TOTAL AS LAST_LANCE,lc.ID AS IDD')
                ->from('lotes as lt')
              //  ->join('(SELECT LOTE_ID,IFNULL(COUNT(LOTE_ID),0) AS IS_SELLER FROM lances_arrematados GROUP BY LOTE_ID) as lca', 'lca.LOTE_ID=lt.ID', 'LEFT')
                ->join('lances as lc','lc.LOTE_ID=lt.ID', 'LEFT')
                //->join('(SELECT ID as IDD,LOTE_ID,TOTAL AS LAST_LANCE FROM lances ORDER BY IDD DESC) as lc', 'lc.LOTE_ID=lt.ID', 'LEFT')
                ->where('lt.ID', $id)
                ->order_by('lc.ID','DESC');
        $row = $this->db->get()->row();
       // if ((int) $row->IS_SELLER == 0):

            $in = $multiply * $row->INCREMENTO;
            $bid = $in + (float) $row->LAST_LANCE;
            //is absolute value lance
            if (isset($user->valor)) {
                $bid = (float) $user->valor;
                $row->LAST_LANCE = TRUE;
            }
            //is primary lance override
            if (is_null($row->LAST_LANCE)) {
                $multiply = 0;
                $in = $multiply * $row->INCREMENTO;
                $bid = $in + $row->LANCE_INICIAL;
            }
            $comission = (($bid * $row->COMISSAO) / 100);
            $bid_comission = $comission + $bid;

            //add lance
            $data = array(
                'LEILAO_ID' => $row->LEILAO_ID,
                'LOTE_ID' => $id,
                'USER_ID' => $user->id,
                'VALOR' => $in,
                'COMISSAO' => $comission,
                'TOTAL' => $bid,
                'TIPO' => $user->tipo,
                'IP' => $this->input->ip_address(),
                'CRIADO' => date('Y-m-d H:i:s'),
                'TOTAL_COMISSAO' => $bid_comission,
                'LOGIN' => $user->login);

          
           $last_id = parent::save($data);


        //endif;
        $this->db->trans_complete();

        if ($this->db->trans_status() == false) {
            return false;
        }
        $data['INSERT_ID'] = $last_id;
        return $data;
    }
    
    /*
     *  getByDataLote
     *  get distinct data lotes with users 
     *  @param int $id
     *  @return array 
     */
    
    function getByDataLote($id){
    	
 $sql =<<<EOD
          SELECT LOGIN,ID,USER_CIDADE,USER_ID,COUNT(ID) AS LANCES,TOTAL AS LANCE,TOTAL_COMISSAO,COMISSAO, lcc.TOTAL_LANCES FROM 
          ( SELECT lci.*,p.CIDADE AS USER_CIDADE FROM lances as lci 
              JOIN profiles as p ON p.USER_ID=lci.USER_ID
              WHERE LOTE_ID=$id ORDER BY ID DESC) as lc ,
          ( SELECT COUNT(ID) AS TOTAL_LANCES  FROM lances WHERE LOTE_ID=$id  ) as lcc 
         GROUP BY USER_ID ORDER BY TOTAL DESC		 
EOD;
    	   $q = $this->db->query($sql);
           $data = $q->result();
           return $data;
        
       }
	
       
       
       public function lotes_in($id){
          $this->db->select('lt.INCREMENTO,lc.*')
                 ->from('lotes as lt')
                 ->join('(SELECT * FROM '
                         . ' ( SELECT * FROM lances ORDER BY ID DESC ) as lcc'
                         . ' GROUP BY LOTE_ID ) AS lc','lc.LOTE_ID=lt.ID')
                 ->where('lt.LEILAO_ID',  $id);
                
          $q = $this->db->get();
          if($q->num_rows() == 0){
              return false;
          }
          return $q->result();             
      } 
      
      

      function by_user_count($uid, $le_id){
                 
        $sql =<<<EOD
          SELECT LOGIN,ID,LOTE_ID,USER_ID,COUNT(ID) AS LANCES,TOTAL AS LANCE,TOTAL_COMISSAO,COMISSAO,lcc.SUPERADOS FROM 
          ( SELECT * FROM lances WHERE LEILAO_ID=$le_id ORDER BY ID DESC) as lc,
          ( SELECT COUNT(*) as SUPERADOS FROM lances where USER_ID=$uid ) as lcc
          GROUP BY LOTE_ID ORDER BY TOTAL DESC        
EOD;
           $q = $this->db->query($sql);             
                  
            
           if($q->num_rows() > 0){
                      
                      $num_ganhadores = 0;
                     foreach ($q->result() as $key => $row) {
                         # code...
                           if($uid == $row->USER_ID){
                             $num_ganhadores +=1; 
                           }

                          

                     }

                     $r = $q->row();

                    $data = new StdClass();

                    $data->LANCES_GANHADORES = $num_ganhadores;
                    $data->LANCES_SUPERADOS  = $r->SUPERADOS - $num_ganhadores; 


              
                     return $data;

           }     
             

             return false;
      }
      
      function get_user_info($id){
          
           $this->db->select('le.TITLE,cm.NOME_FANTASIA,lt.NUM_LOTE,lt.DESCRICAO,lc.*')
                  ->from('lances as lc')
                  ->join('leiloes as le','lc.LEILAO_ID=le.ID')
                  ->join('lotes as lt','lc.LOTE_ID=lt.ID')  
                  ->join('comitentes as cm','cm.ID=le.COMITENTE_ID')
                  ->where('lc.USER_ID',$id)
                  ->order_by('lc.CRIADO','DESC')
                   ;
           
           
            $q = $this->db->get();
          return $q->result();
      }
      
      function info_lote($ltid,$leid) {

        $this->db->select('cm.*,le.DATA,usr.USER_KEY,pf.EMAIL,lt.*,lc.*')
                ->from('lances as lc')
                ->join('lotes as lt', 'lc.LOTE_ID=lt.ID')
                ->join('leiloes as le', 'lt.LEILAO_ID=le.ID')
                ->join('comitentes as cm', 'cm.ID=le.COMITENTE_ID')
                ->join('users as usr','usr.ID=lc.USER_ID')
                ->join('profiles as pf','pf.USER_ID=usr.ID')
                ->where(array(
                    'lc.LOTE_ID' => $ltid,
                    'lc.LEILAO_ID' => $leid))
                ->order_by('lc.ID','DESC')
                ->limit(1);

        $q = $this->db->get();

        return $q->row();
    }
      

    public function delete_all_leilao($id){

      return  $this->db->delete($this->_table_name,array('LEILAO_ID'=>$id));

  }
  
  function last($id){
      
      
    $q =  $this->db->select('p.CIDADE AS USER_CIDADE,lc.*')
              ->from('lances as lc')
              ->join('profiles as p','p.USER_ID=lc.USER_ID')
              ->where(array('LOTE_ID'=>$id))
              ->limit(20)
              ->get();
      
    return $q->result();
  }
}
